//
//  PSFilterDeclarerFirstHandMove.m
//  PrefCore
//
//  Created by Sergey on 6/13/14.
//  Copyright (c) 2014 Play-on-smart. All rights reserved.
//

#import "PSFilter.h"
#import "PSGame.h"

static BOOL CanMoveWithHighestTrump(PSCardRankSet t, PSCardRankSet to) {
    while (t != 0 && to != 0) {
        PSCardRank h  = PSCardSetHighestRank(t);
        PSCardRank ho = PSCardSetNextHigherRank(to, h);
        PSCardRank lo = PSCardSetLowestRank(to);
        if (ho != kRankNull) {
            return NO;
        }
        t = PSCardSetRemoveRank(t, h);
        to = PSCardSetRemoveRank(to, lo);
    }
    return YES;
}

PSHandHash PSFilterDeclarerFirstHandMove(
    PSHandHash candidates
,   PSCardSuit trump
,   PSPlayerId declarer
,   PSHandHash* hands) {
    // get trump suit
    PSCardRankSet t = PSHandGetSuit(candidates, trump);
    PSCardIndex tl = PSCardSetSize(t);
    if (tl == 0) {
        return candidates;
    }
    // Resolve opponents and their combined trump suit
    PSPlayerId p1 = PSGameNextPlayerId(declarer);
    PSPlayerId p2 = PSGameNextPlayerId(p1);
    PSCardRankSet to = PSCardSetCombine(
        PSHandGetSuit(hands[p1], trump)
    ,   PSHandGetSuit(hands[p2], trump)
    );
    // if declarer has trump cards but opponents don't then all trump candidates can be removed
    if (PSCardSetSize(to) == 0) {
        return PSHandRemoveSuit(candidates, trump);
    }
    // if declarer has ace and the total number of trump cards is at least 5, or the declarer has
    // both the ace and the king with at least four trump cards, the first move could be made
    // with the ace, to check how trump cards were dealt between the opponents.
    if (PSCardSetContainsCard(t, kMaskAce) && (tl > 4 || (PSCardSetContainsCard(t, kMaskKing) && tl > 3))) {
        return PSHandWithOneCard([PSCard cardWithSuit:trump andRank:kRankAce]);
    }
    if (CanMoveWithHighestTrump(t, to)) {
        return PSHandWithOneCard([PSCard cardWithSuit:trump andRank:PSCardSetHighestRank(t)]);
    }
    return candidates;
}
